package com.sky.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

@Data
@AllArgsConstructor
@Slf4j
public class TentCosUtil {

    private String region;
    private String secretId;
    private String secretKey;
    private String bucketName;
    private String regoinAddr;

    public String upload(MultipartFile multipartFile, String objectName) {
        // 创建cos实例对象
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置 bucket 的地域, COS 地域的简称请参见 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region regionCos = new Region(region);
        ClientConfig clientConfig = new ClientConfig(regionCos);
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);

        //文件访问路径规则 https://BucketName.regionAddr/ObjectName
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder.append(bucketName).append(".").append(regoinAddr).append("/").append(objectName);

        log.info("文件上传到:{}", stringBuilder.toString());
        // 上传文件
        // 指定要上传的文件,需要将文件临时保存为file类型的文件
        String path = Objects.requireNonNull(this.getClass().getClassLoader().getResource("")).getPath();
        String tempFile = path + "tmpImage";
        File localFile = new File(tempFile);
        if (!localFile.exists()) {
            localFile.mkdirs();
        }
        // 保存在本地的路径
        String localPath = tempFile + "/" + objectName;
        try {
            multipartFile.transferTo(new File(localPath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 指定文件将要存放的存储同桶
        // 指定文件上传到 COS 上的路径，即对象键。例如对象键为 folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
        String key = objectName;
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, new File(localPath));
        cosClient.putObject(putObjectRequest);
        cosClient.shutdown();
        // 删除本地的文件
        File localFileName = new File(localPath);
        localFileName.delete();
        return stringBuilder.toString();
    }
}
